/**
 * 宠币充值配置组件
 * 用于配置宠币充值活动的门槛、赠送比例和促销文案等信息
 */
import React, {Component} from 'react';
import {Checkbox, Form, Input, InputNumber, message, Modal, Radio, Select, Space, Switch} from "antd";
import TheButton from "@/components/TheButton";
import {
    apiPetCoinRechargeConfig,
    apiPetCoinRechargeConfigEdit,
    apiGetDetailByType,
    apiUpdateCapitalConfig
} from '@/request/wallet/rechargeWithdraw'

class PetCoinsPromotion extends Component {
    /**
     * 组件构造函数
     * 初始化组件状态，包括开关状态、模态框可见性等
     */
    constructor(props) {
        super(props)
        this.formRef = React.createRef()
        this.state = {
            switchValue: false,
            switchLoading: false,
            visible: false,
            petCoinRechargeConfigId: null,
            petCoinRechargeConfigData: {},
            openSource: 'button'
        }
    }

    /**
     * 组件挂载后执行的方法
     * 用于获取当前的宠币充值配置信息
     */
    componentDidMount() {
        this.getData()
    }

    /**
     * 获取宠币充值配置信息
     * 调用API获取当前的充值配置，并更新组件状态
     */
    getData = () => {
        apiGetDetailByType({
            dataType: 'CB'
        }).then(res => {
            if (res.code === 0 && res.data) {
                if (res.data.pickType === 'ANOTHER'){
                    res.data.ANOTHER = true
                }
                if (res.data.pickType === 'NEW' || res.data.pickType === 'ANOTHER'){
                    res.data.pickType = 'other'
                }
                this.setState({
                    petCoinRechargeConfigData: res.data,
                    switchValue: res.data.configState === "Y",
                })
            }
        })
    }

    /**
     * 开关变化时的处理函数
     * 根据开关状态决定是弹出模态框确认保存还是直接请求保存
     * @param e 开关状态
     */
    switchChange = async (e) => {
        if (e) {
            // 开启时需要弹出模态框确认保存
            this.setState({
                openSource: 'switch'
            })
            this.openModal()
        } else {
            // 关闭时直接请求保存
            let res = await apiUpdateCapitalConfig({
                configId: this.state.petCoinRechargeConfigData.configId,
                configState: "N",
                dataType: 'CB'
            })
            if (res.code === 0) {
                message.success('修改成功')
                this.getData()
            }
        }
    }

    /**
     * 打开模态框
     * 设置模态框为可见，并根据当前的配置数据设置表单的默认值
     */
    openModal = () => {
        let data = this.state.petCoinRechargeConfigData
        this.setState({visible: true}, () => {
            this.formRef.current.setFieldsValue({...data})
        })
    }

    /**
     * 关闭模态框
     * 重置模态框可见性和表单数据
     */
    closeModal = () => {
        this.setState({visible: false, openSource: 'button'})
        this.formRef.current.resetFields()
    }

    /**
     * 表单值变化时的处理函数
     * 根据表单字段的变化重置其他字段的值或可见性
     * @param value 当前变化的表单字段值
     * @param allValue 所有表单字段的值
     */
    onValuesChange = (value, allValue) => {
        // 根据特定字段的值变化重置其他字段
        if ('pickType' in value) {
            this.formRef.current.resetFields()
            this.formRef.current.setFieldsValue({pickType: value.pickType})
        }
        // if ('definitionPickByNew' in value) {
        //     if (value.definitionPickByNew === 1) {
        //         this.formRef.current.resetFields(["limitNumberByNew"])
        //     }
        //     if (value.definitionPickByNew === 2) {
        //         this.formRef.current.resetFields(["registerDaysByNew"])
        //     }
        // }
        // if ('ANOTHER' in value) {
        //     if (!value.ANOTHER) {
        //         this.formRef.current.resetFields(['firstThresholdByAnother', 'priceRatioByAnother', 'promotionOfficialByAnother'])
        //     }
        // }
    }

    /**
     * 表单提交的处理函数
     * 验证表单数据并根据验证结果执行保存操作
     * @param values 表单提交的值
     */
    onFinish = async (values) => {
        await this.formRef.current.validateFields().then(async (values) => {
            let {openSource, petCoinRechargeConfigData} = this.state;
            let params = {
                "configId": petCoinRechargeConfigData.configId,
                "dataType": 'CB',
                ...values
            }
            // 根据不同选项设置pickType
            if (values.NEW) {
                params.pickType = 'NEW'
            }
            if (values.ANOTHER) {
                params.pickType = 'ANOTHER'
            }
            // 如果是开关操作，则请求开启配置
            if (openSource === 'switch') {
                params.configState = "Y"
            }
            // console.log({...params})
            // 执行保存请求
            apiUpdateCapitalConfig({...params}).then(async (res) => {
                if (res.code === 0) {
                    message.success('保存成功')
                    await this.getData()
                    await this.closeModal()
                }
            })

        })
    }

    /**
     * 根据指定字段名和必填标志生成表单项
     * 用于生成充值门槛、赠送比例和促销文案的表单项
     * @param names 字段名数组
     * @param requireFlag 是否必填
     * @returns JSX.Element
     */
    allFormItemTemplate = (names, requireFlag) => {
        if (names) {
            return <>
                <Form.Item label="门槛" required={requireFlag}>
                    <span className="ant-form-text">单笔充值满</span>
                    <Form.Item
                        name={names[0]}
                        noStyle
                        rules={[
                            {
                                required: requireFlag,
                                message: '请输入1~99999范围内的整数!',
                            },
                        ]}
                        getValueProps={v => ({value: v ? React.$transNum(v, 2, -2) : v, v})}
                        getValueFromEvent={e => e ? e * 100 : e}
                    >
                        <InputNumber style={{width: 100}} min={1} max={99999} precision={0}/>
                    </Form.Item>
                    <span className="ant-form-text">元</span>
                </Form.Item>
                <Form.Item label="赠送比例" required={requireFlag}
                           extra="例如：设置10%，用户购买6元，可获得66个宠币，其中6个为平台赠送">
                    <Form.Item
                        name={names[1]}
                        noStyle
                        rules={[
                            {
                                required: requireFlag,
                                message: '请输入1~30范围内的整数!',
                            },
                        ]}
                    >
                        <InputNumber style={{width: 180}} min={1} max={30} precision={0}/>
                    </Form.Item>
                    <span className="ant-form-text">%</span>
                </Form.Item>
                <Form.Item
                    label="促销文案"
                    name={[names[2]]}
                >
                    <Input.TextArea style={{width: 180}} maxLength={20} showCount/>
                </Form.Item>
            </>
        }
    }

    /**
     * 生成其他用户表单项
     * 用于生成新用户和其他用户范围的表单配置
     * @returns JSX.Element
     */
    otherFormItemTemplate = () => {
        return <>
            <Form.Item
                name="NEW"
                valuePropName="checked"
                wrapperCol={{
                    offset: 4,
                    span: 16,
                }}
                initialValue={true}
            >
                <Checkbox disabled>新用户</Checkbox>
            </Form.Item>
            <Form.Item
                name="definitionPickByNew"
                wrapperCol={{
                    offset: 5,
                    span: 16,
                }}
                rules={[
                    {
                        required: true,
                        message: '请选择新用户定义',
                    },
                ]}
            >
                <Radio.Group>
                    <Space direction="vertical">
                        <Radio value={1}>
                            <span className="ant-form-text">定义1：注册</span>
                            <Form.Item
                                noStyle
                                shouldUpdate={(prevValues, currentValues) => prevValues.definitionPickByNew !== currentValues.definitionPickByNew}
                            >
                                {({getFieldValue}) => {
                                    return <Form.Item
                                        name="registerDaysByNew"
                                        noStyle
                                        rules={[
                                            {
                                                required: getFieldValue('definitionPickByNew') === 1,
                                                message: '请输入值范围1~999范围内的整数!',
                                            },
                                        ]}
                                    >
                                        <InputNumber style={{width: 80}} min={1} max={999} precision={0}/>
                                    </Form.Item>
                                }}
                            </Form.Item>
                            <span className="ant-form-text">天内</span>
                        </Radio>
                        <Radio value={2}>
                            <span className="ant-form-text">定义2：前</span>
                            <Form.Item
                                noStyle
                                shouldUpdate={(prevValues, currentValues) => prevValues.definitionPickByNew !== currentValues.definitionPickByNew}
                            >
                                {({getFieldValue}) => {
                                    return <Form.Item
                                        name="limitNumberByNew"
                                        noStyle
                                        rules={[
                                            {
                                                required: getFieldValue('definitionPickByNew') === 2,
                                                message: '请输入值范围1~999范围内的整数!',
                                            },
                                        ]}
                                    >
                                        <InputNumber style={{width: 80}} min={1} max={999} precision={0}/>
                                    </Form.Item>
                                }}
                            </Form.Item>
                            <span className="ant-form-text">次宠币充值</span>
                        </Radio>
                    </Space>
                </Radio.Group>
            </Form.Item>
            <div style={{marginLeft: 120}}>
                {this.allFormItemTemplate(['firstThresholdByNew', 'priceRatioByNew', 'promotionOfficialByNew'], true)}
            </div>
            <Form.Item
                name="ANOTHER"
                valuePropName="checked"
                wrapperCol={{
                    offset: 4,
                    span: 16,
                }}
            >
                <Checkbox>其他用户</Checkbox>
            </Form.Item>
            <Form.Item
                noStyle
                shouldUpdate={(prevValues, currentValues) => prevValues.ANOTHER !== currentValues.ANOTHER}
            >
                {({getFieldValue}) => {
                    return <div style={{marginLeft: 120}}>
                        {this.allFormItemTemplate(['firstThresholdByAnother', 'priceRatioByAnother', 'promotionOfficialByAnother'], getFieldValue('ANOTHER'))}
                    </div>
                }}
            </Form.Item>
        </>
    }
    promotionOfficial = () => {
        let { petCoinRechargeConfigData: data } = this.state;
        let doms = []
        if (data.pickType === 'other') {
            if (data.definitionPickByNew === 1) {
                doms.push(
                    <div>
                        新用户：注册{data.registerDaysByNew}天内，单笔充值满{React.$transNum(data.firstThresholdByNew, 2, -2)}元，赠送{data.priceRatioByNew}%额外宠币。活动促销文案：{data.promotionOfficialByNew}
                    </div>
                )
            }
            if (data.definitionPickByNew === 2) {
                doms.push(
                    <div>
                        新用户：前{data.limitNumberByNew}次宠币充值，单笔充值满{React.$transNum(data.firstThresholdByNew, 2, -2)}元，赠送{data.priceRatioByNew}%额外宠币。活动促销文案：{data.promotionOfficialByNew}
                    </div>
                )
            }
            if (data.ANOTHER) {
                doms.push(
                    <div>
                        其他用户：单笔充值满{React.$transNum(data.firstThresholdByAnother, 2, -2)}元，赠送{data.priceRatioByAnother}%额外宠币。活动促销文案：{data.promotionOfficialByAnother}
                    </div>
                )
            }
        }
        if (data.pickType === 'ALL'){
            doms.push(
                <div>
                    所有人：单笔充值满{React.$transNum(data.firstThresholdByAll, 2, -2)}元，赠送{data.priceRatioByAll}%额外宠币。活动促销文案：{data.promotionOfficialByAll}
                </div>
            )
        }
        return doms
    }

    render() {
        const {switchValue, switchLoading, visible} = this.state
        return (
            <div style={{marginTop: '20px'}}>
                <Space size={20}>
                    <span>宠币充值促销</span>
                    <Switch
                        checked={switchValue}
                        onChange={(e) => this.switchChange(e)} loading={switchLoading}
                    />
                    <span style={{color: 'grey', fontSize: '12px'}}>仅对安卓和H5充值有效</span>
                </Space>
                <br/>
                <div style={{marginTop: '20px'}}>
                    {this.promotionOfficial()}
                </div>
                <div style={{marginTop: '20px', marginLeft: '300px'}}>
                    <TheButton
                        haspermi={["wallet:petCoinsPromotion:edit"]}
                        type="primary"
                        onClick={() => this.openModal()}
                    >
                        编辑
                    </TheButton>
                </div>
                <Modal
                    width={600}
                    open={visible}
                    title={"宠币充值促销活动"}
                    maskClosable={false}
                    onCancel={() => this.closeModal()}
                    onOk={() => this.onFinish()}
                >
                    <Form
                        ref={this.formRef}
                        preserve={false}
                        labelCol={{
                            span: 5,
                        }}
                        wrapperCol={{
                            span: 19
                        }}
                        onValuesChange={this.onValuesChange}
                    >
                        <Form.Item
                            name="pickType"
                            label="用户范围"
                            rules={[
                                {
                                    required: true,
                                },
                            ]}
                        >
                            <Select placeholder="请选择用户范围" style={{width: 180}}>
                                <Select.Option value="ALL">所有人</Select.Option>
                                <Select.Option value="other">指定用户</Select.Option>
                            </Select>
                        </Form.Item>
                        <Form.Item
                            noStyle
                            shouldUpdate={(prevValues, currentValues) => prevValues.pickType !== currentValues.pickType}
                        >
                            {({getFieldValue}) => {
                                if (getFieldValue('pickType') === 'ALL') {
                                    return this.allFormItemTemplate(['firstThresholdByAll', 'priceRatioByAll', 'promotionOfficialByAll'], true)
                                } else if (getFieldValue('pickType') === 'other') {
                                    return this.otherFormItemTemplate
                                }
                            }}
                        </Form.Item>
                    </Form>
                </Modal>
            </div>
        );
    }
}

export default PetCoinsPromotion;
